package com.alinesno.cloud.operation.cmdb.common.jobs;

import java.sql.Timestamp;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alinesno.cloud.operation.cmdb.common.constants.OrderStatusEnum;
import com.alinesno.cloud.operation.cmdb.common.constants.ParamsEnum;
import com.alinesno.cloud.operation.cmdb.entity.OrdersEntity;
import com.alinesno.cloud.operation.cmdb.repository.OrderRepository;
import com.alinesno.cloud.operation.cmdb.service.OrderRecordService;
import com.alinesno.cloud.operation.cmdb.service.ParamsService;
import com.alinesno.cloud.operation.cmdb.third.wechat.WechatService;


/**
 * 定时任务,判断订单是否超时
 * 
 * @author WeiXiaoJin
 * @since 2018年8月11日 下午12:37:58
 */
@Component
public class OrderOuttimeJob{
	
	private static final Logger logger = LoggerFactory.getLogger(OrderOuttimeJob.class) ;
	 
	@Autowired
	private ParamsService paramsService ; 
	
	@Autowired
	private WechatService wechatService ; 
	
	@Autowired
	private OrderRecordService orderRecordService ; //订单记录服务 
	
	@Autowired
	private OrderRepository orderRepository ; 

	// 每分钟做一次订单表扫描，并查询出未接的订单，并判断时间是否超过时间 
	@Scheduled(cron = "0 0/1 * * * ?")
	public void timerToNow() {
		
		//查询所有未接的订单
		List<OrdersEntity> list = orderRepository.findBySendStatus(OrderStatusEnum.ORDER_PENDING.getCode()) ; 
		
		if(list != null) {
			
			logger.debug("超时订单扫描查询任务,未接订单量:{}" , list.size());
			
			for(OrdersEntity e : list) {
				
				int outTime = paramsService.findParamByNameToInt(ParamsEnum.ORDER_OUTTIME.getCode() , e.getMasterCode())  ; 
				
				//判断是否超时
				long startTime = e.getAddTime().getTime() ;
				long now = System.currentTimeMillis() ; 
				long time = (now - startTime)/1000 ; 
			
				String logDetail = String.format("订单:%s 未有接单,间隔时间:%s,超时时间:%s", e.getOrderId() , time , outTime) ; 
				logger.debug(logDetail) ; 
				
				if((time) > outTime) { //设置订单超时
					e.setSendStatus(OrderStatusEnum.ORDER_OUTTIME.getCode()); 
					e.setUpdateTime(new Timestamp(System.currentTimeMillis()));
					
					orderRepository.save(e) ; 
					orderRecordService.saveRecord(e.getOrderId(), OrderStatusEnum.ORDER_OUTTIME.code , e.getUserId() , logDetail); //保存订单记录
					
					//超时订单给用户发送提醒
					wechatService.sendTaskReceive(e.getOrderId());
				} 
				/*else {
					wechatService.sendTaskMessageToSchool(e.getOrderId() , null, e.getMasterCode()); 
				}
				*/
			}
		}
	}

}